import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookie from 'js-cookie'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'main',
    component: () => import('../views/Main.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/layout',
    name: 'layout',
    //重定向到home
    redirect: '/layout/home',
    component: () => import('../components/Layout.vue'),
    // 子路由
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import('../views/Home.vue')
      },
      {
        path: 'pc',
        name: 'PersonalCenter',
        component: () => import('../views/PersonalCenter.vue')
      },
      {
        path:'addUser',
        name:'addUser',
        component:()=>import('../views/AddUser.vue')
      },
      {
        path:'addPro',
        name:'addPro',
        component:()=>import('../views/AddPro.vue')
      },
      {
        path:'addTask',
        name:'addTask',
        component:()=>import('../views/AddTask.vue')
      },
    ]
  },
  {
    path: '/aside',
    name: 'CommonAside',
    component: () => import('../components/CommonAside.vue')
  },
  {
    path: '/pc',
    name: 'PersonalCenter',
    component: () => import('../views/PersonalCenter.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})


// 全局前置路由守卫：初始化和每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  // 获取token
  const token = Cookie.get("token");
  if (to.name === "register" || to.name === "login" || to.name === "main") {
    next()
  }
  else
    // 当token不存在且不在登录页
    if (!token && to.name !== "login") {
      next({ name: 'login' })
      // 当token存在且在登录页
    }
    else if ((token && to.name == 'login') || (token && to.name == 'register')) {
      next({ name: 'layout' })
    } else {
      next()
    }
})


export default router